package com.llan;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import org.junit.Test;

import java.util.concurrent.Future;

import static org.junit.Assert.assertEquals;

/**
 * Created by java_long on 2018/5/18 18:22.
 */
public class HystrixHelloWorldFallback extends HystrixCommand<String> {
    private final String name;

    public HystrixHelloWorldFallback(String name) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.name = name;
    }

    @Override
    protected String run() {
        throw new RuntimeException("模拟出现异常!");
    }

    @Override
    protected String getFallback() {
        return "Hello Failure " + name + "!";
    }

    public static class UnitTest {

        @Test
        public void testSynchronous() {
            assertEquals("Hello Failure World!", new HystrixHelloWorldFallback("World").execute());
            assertEquals("Hello Failure Bob!", new HystrixHelloWorldFallback("Bob").execute());
        }

        @Test
        public void testAsynchronous1() throws Exception {
            assertEquals("Hello Failure World!", new HystrixHelloWorldFallback("World").queue().get());
            assertEquals("Hello Failure Bob!", new HystrixHelloWorldFallback("Bob").queue().get());
        }

        @Test
        public void testAsynchronous2() throws Exception {

            Future<String> fWorld = new HystrixHelloWorldFallback("World").queue();
            Future<String> fBob = new HystrixHelloWorldFallback("Bob").queue();

            assertEquals("Hello Failure World!", fWorld.get());
            assertEquals("Hello Failure Bob!", fBob.get());
        }
    }
}

